package com.onstar.cn.common.util;

import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.widget.AbsListView;
import android.widget.ListView;

import java.lang.reflect.Method;

/**
 * Created by kai zhang on 2015/12/10.
 */
public class HacksUtils {
    static Method listViewTrackMotionScroll;
    static Method stateListDrawableGetStateDrawable;

    private static void initListViewTrackMotionScroll() {
        Method trackMotionScroll = null;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            try {
                trackMotionScroll = AbsListView.class
                        .getDeclaredMethod("trackMotionScroll", int.class, int.class);
                trackMotionScroll.setAccessible(true);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
        listViewTrackMotionScroll = trackMotionScroll;
    }

    public static void scrollListBy(ListView listView, int y) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            listView.scrollListBy(y);
        } else {
            if (listViewTrackMotionScroll == null) {
                initListViewTrackMotionScroll();
            }
            try {
                listViewTrackMotionScroll.invoke(listView, -y, -y);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static void initStateListDrawableGetStateDrawable() {
        Method getStateDrawable = null;
        try {
            getStateDrawable = StateListDrawable.class
                    .getDeclaredMethod("getStateDrawable", int.class);
            getStateDrawable.setAccessible(true);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        stateListDrawableGetStateDrawable = getStateDrawable;
    }

    public static Drawable getStateDrawable(StateListDrawable stateListDrawable, int index) {
        if (stateListDrawableGetStateDrawable == null) {
            initStateListDrawableGetStateDrawable();
        }
        try {
            return (Drawable) stateListDrawableGetStateDrawable.invoke(stateListDrawable, index);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
